package LeetCode.leetcode;

import java.util.LinkedList;
import java.util.Set;

import com.google.common.collect.Sets;

/**
 * @author leiwenkang <leiwenkang@kuaishou.com>
 * Created on 2022-08-01
 */
public class Test353SnakeGame {
    private LinkedList<Pos> snake = new LinkedList<>();
    private int height;
    private int width;

    private Set<Pos> board = Sets.newHashSet();

    private int[][] food;
    private int eat;

    public Test353SnakeGame(int height, int width, int[][] food) {
        this.height = height;
        this.width = width;
        this.food = food;
        Pos pos = new Pos(0, 0);
        snake.add(pos);
        board.add(pos);
        eat = 0;
    }

    private boolean eat(int x, int y) {
        if (eat >= food.length) {
            return false;
        }

        if (food[eat][0] < 0 || food[eat][0] >= width || food[eat][1] < 0 || food[eat][1] >= height) {
            return false;
        }

        if (x == food[eat][0] && y == food[eat][01]) {
            return true;
        }

        return false;
    }


    private int remove(Direction direction) {
        Pos head = snake.getFirst();
        Pos next = new Pos(head.x, head.y);

        if (direction == Direction.L) {
            next.x--;
        } else if (direction == Direction.R) {
            next.x++;
        } else if (direction == Direction.U) {
            next.y++;
        } else if (direction == Direction.D) {
            next.y--;
        } else {
            return -1;
        }

        if (next.x < 0 || next.x >= width || next.y < 0 || next.y >= height) {
            return -1;
        }

        if (eat(next.x, next.y)) {
            snake.addFirst(next);
            board.add(next);
            eat++;
            return eat;
        }

        Pos tail = snake.getLast();
        board.remove(tail);
        snake.removeLast();

        if (board.contains(next)) {
            return -1;
        }

        snake.addFirst(next);
        board.add(next);
        return eat;

    }
}

enum Direction {
    L,
    R,
    U,
    D;
}

class Pos {
    int x;
    int y;

    public Pos(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return x + "," + y ;
    }
}
